#pragma once
#include <vector>
#include "mysql.hpp"
#include "logger.hpp"
#include "friend_apply.hxx"
#include "friend_apply-odb.hxx"

namespace zzy_mims
{
    class FriendApplyTable
    {
    public:
        using ptr = std::shared_ptr<FriendApplyTable>;
        FriendApplyTable(const std::shared_ptr<odb::core::database>& db):_db(db){};
        bool insert(FriendApply& fa)
        {
            try
            {
                odb::transaction trans(_db->begin());
                _db->persist(fa);
                trans.commit();
            }catch(std::exception& e)
            {
                LOG_ERROR("新增好友申请失败{}-{}:{}",fa.sender_id(),fa.accepter_id(),e.what());
                return false;
            }
            return true;
        }
        bool exist(const std::string& sender_id,const std::string& accepter_id)
        {
            bool flag =0;
            try
            {
                using query = odb::query<FriendApply>;
                using result = odb::result<FriendApply>;
                odb::transaction trans(_db->begin());

                result r(_db->query<FriendApply>(query::sender_id==sender_id
                    &&query::accepter_id==accepter_id));
                flag = !r.empty();//提交事务后r会销毁，因此需提前保存查询结果
                trans.commit();
            }catch(std::exception& e)
            {
                LOG_ERROR("获取好友申请失败,{}-{}:{}",sender_id,accepter_id,e.what());
                return false;
            }
            return flag;
        }
        bool remove(const std::string& sender_id,const std::string& accepter_id)
        {
            try
            {
                odb::transaction trans(_db->begin());
                _db->erase_query<FriendApply>(odb::query<FriendApply>::sender_id==sender_id
                    &&odb::query<FriendApply>::accepter_id==accepter_id);
                trans.commit();
            }catch(std::exception& e)
            {
                LOG_ERROR("删除好友申请失败,{}-{}:{}",sender_id,accepter_id,e.what());
                return false;
            }
            return true;
        }
        //获取指定uid的所有好友申请的uid
        std::vector<std::string> applyUsers(const std::string& uid)
        {
            std::vector<std::string> users;
            try
            {
                using query = odb::query<FriendApply>;
                using result = odb::result<FriendApply>;
                odb::transaction trans(_db->begin());

                result r(_db->query<FriendApply>(query::accepter_id==uid));
                for(auto fa:r)
                users.emplace_back(fa.sender_id());
                trans.commit();
            }catch(std::exception& e)
            {
                LOG_ERROR("获取用户:{}的好友申请失败:{}",uid,e.what());
            }
            return users;
        }



    private:
        std::shared_ptr<odb::core::database> _db;
    };
}